package com.useful.secure.auth;

import com.google.common.collect.Lists;
import com.useful.core.constant.TokenConstant;
import com.useful.core.pool.StringPool;
import com.useful.core.utils.Func;
import com.useful.secure.entity.User;
import com.useful.secure.utils.SecureUtil;

import java.util.List;

/**
 * @author : wenchao.long
 * @date : Created in 2021/9/23 20:03 周四
 * @description :
 */
public class AuthFun {

    /**
     * 放行所有请求
     *
     * @return true
     */
    public boolean permitAll() {
        return true;
    }

    /**
     * 只有超管角色才可访问
     *
     * @return {boolean}
     */
    public boolean denyAll() {
        return hasRole(TokenConstant.ADMIN);
    }

    /**
     * 判断是否有该角色权限
     *
     * @param role 单角色
     * @return {boolean}
     */
    public boolean hasRole(String role) {
        return hasAnyRole(role);
    }

    /**
     * 判断是否有该角色权限
     *
     * @param role 角色集合
     * @return {boolean}
     */
    public boolean hasAnyRole(String... role) {
        List<String> roles = Lists.newArrayList(role);
        return hasAnyRole(roles);
    }

    private boolean hasAnyRole(List<String> role) {
        User user = SecureUtil.getUser();
        if (user == null) {
            return false;
        }
        String roleName = user.getRoleName();
        if (Func.isEmpty(roleName)) {
            return false;
        }
        String[] strings = roleName.split(StringPool.COMMA);
        List<String> roleNames = Lists.newArrayList(strings);
        return hsElements(roleNames, role);
    }

    private boolean hsElements(List<String> l1, List<String> l2) {
        if (Func.isEmpty(l1) || Func.isEmpty(l2)) {
            return false;
        }
        int len1 = l1.size();
        int len2 = l2.size();
        if (len1 > len2) {
            return hsElements(l2, l1);
        }
        for (String s1 : l1) {
            for (String s2 : l2) {
                if (s1 != null && s1.equals(s2)) {
                    return true;
                }
            }
        }
        return false;
    }
}
